package com.htt.bms.security;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.htt.bms.dao.system.SysUserDao;
import com.htt.bms.domain.sys.SysUser;
import com.htt.bms.utils.SecurityUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsPasswordService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.provisioning.UserDetailsManager;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;

/**
 * @author 侯婷婷
 * @version 1.0
 * @description UserDetailsService实现类/测试
 */
@Service
public class DBUserDetailsManager implements UserDetailsManager, UserDetailsPasswordService {

    @Resource
    private SysUserDao sysUserDao;

    @Override
    public UserDetails updatePassword(UserDetails userDetails, String s) {
        return null;
    }

    @Override
    public void createUser(UserDetails userDetails) {

    }

    @Override
    public void updateUser(UserDetails userDetails) {

    }

    @Override
    public void deleteUser(String s) {

    }

    @Override
    public void changePassword(String s, String s1) {

    }

    @Override
    public boolean userExists(String s) {
        return false;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getUsername, username);

        SysUser sysUser = sysUserDao.selectOne(queryWrapper);

        if (sysUser == null){
            throw new UsernameNotFoundException(username);
        }else {
            //TODO 可能有错
            /*SecurityUtils user = new SecurityUtils(sysUser);
            return user;*/
            //SecurityUtils user = new SecurityUtils(sysUser);
            Collection<GrantedAuthority> authorities = new ArrayList<>();
            return new User(
                    sysUser.getUsername(),
                    sysUser.getPassword(),
                    true,
                    true,
                    true,
                    true,
                    authorities
            );
        }
    }
}
